import React, { useEffect, useState } from 'react'
import { useParams, NavLink } from 'react-router-dom'
import { MyContext } from '../../context/index'
const Index = () => {
    // 1. 获取动态参数 
    const { id } = useParams();
    const [item, setItem] = useState({})
    // 2. 请求函数
    const fetchItem = () => {
        fetch('/api/detail/' + id).then(resp => resp.json()).then(data => {

            console.log(data)
            setItem(data.data)
        })
    }

    useEffect(() => {
        fetchItem()
    }, [])

    const addCar = (carList, setCarList) => {
        setCarList([...carList, carList.length + 1])
    }
    return (
        <div>
            <div>
                <div>详情--{id}</div>
                <img src={item.image} alt="" />
                <h2>{item.title}</h2>
                <MyContext.Consumer>
                    {
                        ({ carList, setCarList }) => {
                            return  <button onClick={() => addCar(carList, setCarList)}>加入购物车</button>
                        }
                    }
                </MyContext.Consumer>
                <NavLink to="/car">car</NavLink>
            </div>
        </div>

    )
}

export default Index